package com.framework.spring.bpp.bean;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;

@Slf4j(topic = "e")
@Component
public class BeanPostProcessorNormalUpdate implements BeanPostProcessor, InitializingBean {

	@Autowired
	private BeanPostProcessorService beanPostProcessorService;

	public BeanPostProcessorNormalUpdate() {
		log.info("BeanPostProcessorNormalUpdate constrcut-{}", beanPostProcessorService);
	}

	@PostConstruct
	public void postConstruct() {
		log.info("BeanPostProcessorNormalUpdate postConstruct-{}", beanPostProcessorService);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		log.info("BeanPostProcessorNormalUpdate afterPropertiesSet-{}", beanPostProcessorService);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if ("beanPostProcessorService".equals(beanName)) {
			Class<?> clazz = bean.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				if ("str".equals(field.getName())) {
					field.setAccessible(true);
					try {
						field.set(bean, "spring0");
					} catch (IllegalAccessException e) {
						throw new RuntimeException(e);
					}
				}
			}
			return bean;
		}
		return null;
	}
}
